package com.zyz.common.security.handler;

import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.core.model.Result;
import com.zyz.common.security.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.Objects;

import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 请求方法不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                         HttpServletRequest request) {
        log.error("请求地址'{}',不支持'{}'请求", request.getRequestURL(), e.getMessage());
        return Result.fail(ResultCodeEnum.ERROR);
    }


    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生运行时异常: {}", request.getRequestURL(), e.getMessage(),e);
        return Result.fail(ResultCodeEnum.ERROR);
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result<?> handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生服务异常: {}", request.getRequestURL(), e.getMessage(), e);
        return Result.fail(e.getCode(),e.getMessage());
    }


    /**
     * 拼接validation的异常返回信息
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        log.error(e.getMessage());
        String message = join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return Result.fail(ResultCodeEnum.FAILED_PARAMS_VALIDATE.getCode(), message);
    }

    private <E> String join(Collection<E> collection, Function<E, String>
            function, CharSequence delimiter) {
        if (collection == null || collection.isEmpty()) {
            return "";
        }
        return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址'{}'发生异常: {}", request.getRequestURL(), e.getMessage());
        return Result.fail(ResultCodeEnum.ERROR);
    }


}
